package com.kx.controller;

import com.kx.bean.Car;
import com.kx.bean.Email;
import com.kx.bean.User;
import com.kx.config.MyUtils;
import com.kx.service.CarService;
import com.kx.service.UserService;
import com.kx.service.impl.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private MailService mailService;

    @Autowired
    private CarService carService;

    @RequestMapping("user_login")
    public String userLogin() {
        return "user_login";
    }

    @RequestMapping("user/reserve")
    public String reserve() {
        return "user/reserve";
    }

    /**
     * 前台：根据前端传来的 username,password 查询用户，成功返回首页，否则返回用户登录页
     */
    @RequestMapping("userLoginValidate")
    @ResponseBody
    public int loginValidate(String username, String password, HttpSession session) {
        User user = userService.selectByUsernameAndPassword(username, password);
        ModelAndView mv = new ModelAndView();
        session.setAttribute("user", user);
        mv.setViewName("reserve");
        if (user != null) {
            return 1;
        }
        return 0;
    }
//    @RequestMapping("loginValidate")
//    public String login(String username, String password, Model model){
//        Subject subject = SecurityUtils.getSubject();
//        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
//        try{
//            subject.login(token);
//            return "index";
//        }catch (UnknownAccountException e){
//            model.addAttribute("msg1","用户名错误");
//            return "login";
//        }catch (IncorrectCredentialsException e){
//            model.addAttribute("msg2","密码错误");
//            return "login";
//        }
//    }

    @RequestMapping("/sendMe")
    public String sendMe() {
        return "sendMe";
    }

    /**
     * 邮件多人发送文字及图片
     */
    @RequestMapping("/send")
    @ResponseBody
    public int send(Email email, @RequestParam(value = "file_image", required = false) MultipartFile multipartFile) throws MessagingException {
        List<User> users = userService.findBlackData2();
        List<String> emails = new ArrayList<>();
        for (User user : users) emails.add(user.getEmail());

        String[] to = emails.toArray(new String[0]);
        // 调用utils层的方法进行文件上传处理进行查询操作
        if (multipartFile.isEmpty()) {
            mailService.sendSimpleTextMail(to, email.getSubject(), email.getContent());
        } else {
            String imgPath = MyUtils.doSingleFileUpload1(multipartFile, "sendInfoFile", "sendInfo-", email, "image");

            String content =
                    "<br/><img src='cid:test001'>";
//            mailService.sendImgSingle(to, email.getSubject(), email.getContent() + content, "target/classes/static/sendInfoFile/" + imgPath, "test001");
            mailService.sendImgSingle(to, email.getSubject(), email.getContent() + content, "sendInfoFile/" + imgPath, "test001");
        }
        return 1;
    }

    @RequestMapping(value = "/findAllUsers", method = RequestMethod.GET)
    @ResponseBody
    public Object findUserData(@RequestParam("page") Integer page, @RequestParam("limit") Integer limit) {
        return userService.findData(page, limit);
    }

    /**
     * 通过用户id查找对应预订的车位号
     *
     * @param uid
     * @return
     */
    @RequestMapping("/getSiteById")
    @ResponseBody
    public Object findById(@RequestParam("uid") Integer uid) {
        return userService.findById(uid);
    }

    @RequestMapping(value = "/updateUser", method = {RequestMethod.PUT, RequestMethod.POST})
    @ResponseBody
    public int updateUser(User user, Car car) {
        int i = 0;
        if (carService.findCarByLicensePlate(car.getLicensePlate()) == null) {
            int getCid = carService.saveCarAndGetCid(car);
            user.setCid(getCid);
        }
        i = userService.updateUser(user);
        return i;
    }

    /**
     * 后台：根据前端传来的信息停用一个用户，数据库里还保存此人信息（本质update）
     */
    @RequestMapping("/deleteUser")
    @ResponseBody
    public Object deleteUser(Integer uid) {
        return userService.deleteUser(uid);
    }

    /**
     * 后台：根据前端传来的信息新增一个用户
     */
    @PostMapping("/addUser")
    @ResponseBody
    public int ajaxAddUser(User user) {
        int a = 0;
        if (user != null) {
            a = userService.saveUser(user);
        }
        return a;
    }

    @RequestMapping("user/register")
    public String register() {
        return "user/register";
    }

    @RequestMapping("/register")
    public ModelAndView register(String username, String password) {
        ModelAndView modelAndView = new ModelAndView();
        User user1 = this.userService.queryUserByName(username);
        if (user1 != null) {
            modelAndView.addObject("error", "用户名已存在！");
            modelAndView.setViewName("user/register");
        } else {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            int i = this.userService.saveUser(user);
            modelAndView.setViewName("user/register_result");
        }
        return modelAndView;
    }

}